<template>
  <el-drawer
    v-model="visible"
    title="客户详情"
    size="50%"
    @close="handleClose"
  >
    <el-tabs v-model="activeTab">
      <el-tab-pane label="基本信息" name="basic">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="客户名称">
            {{ customer.name }}
          </el-descriptions-item>
          <el-descriptions-item label="客户编码">
            {{ customer.code }}
          </el-descriptions-item>
          <el-descriptions-item label="客户类型">
            {{ getCustomerTypeText(customer.type) }}
          </el-descriptions-item>
          <el-descriptions-item label="客户等级">
            <el-tag :type="customer.level === 'vip' ? 'danger' : customer.level === 'important' ? 'warning' : 'info'">
              {{ getCustomerLevelText(customer.level) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户状态">
            <el-tag :type="getCustomerStatusType(customer.status)">
              {{ getCustomerStatusText(customer.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户来源">
            {{ getCustomerSourceText(customer.customerSource) }}
          </el-descriptions-item>
          <el-descriptions-item label="负责销售">
            {{ customer.responsibleSalesman || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="信用评级">
            {{ customer.creditRating }}
          </el-descriptions-item>
          <el-descriptions-item label="信用分">
            {{ customer.creditScore }}
          </el-descriptions-item>
          <el-descriptions-item label="客户价值">
            <el-rate
              v-model="customer.customerValue"
              disabled
              :max="5"
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            />
          </el-descriptions-item>
          <el-descriptions-item label="订单数">
            {{ customer.orderCount }}
          </el-descriptions-item>
          <el-descriptions-item label="总金额">
            ¥{{ formatAmount(customer.totalAmount) }}
          </el-descriptions-item>
          <el-descriptions-item label="平均订单金额">
            ¥{{ formatAmount(customer.avgOrderAmount) }}
          </el-descriptions-item>
          <el-descriptions-item label="未开票金额">
            ¥{{ formatAmount(customer.uninvoicedAmount) }}
          </el-descriptions-item>
          <el-descriptions-item label="最近订单">
            {{ customer.lastOrderDate ? formatDate(customer.lastOrderDate) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ customer.remark || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatDate(customer.createdAt) }}
          </el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>
      
      <el-tab-pane label="联系人" name="contacts">
        <el-table :data="customer.contactPersons" style="width: 100%">
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="department" label="部门" width="120" />
          <el-table-column prop="position" label="职位" width="120" />
          <el-table-column prop="phone" label="电话" width="120" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="remark" label="备注" />
        </el-table>
      </el-tab-pane>
    </el-tabs>
    
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleEdit">编辑</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
// @ts-nocheck
import { ref, watch, computed } from '@vue/runtime-core'
import type { Customer, ContactPerson } from '@/types/customer'

interface CustomerDetail {
  id: string
  name: string
  code: string
  type: string
  level: string
  status: string
  contactPersons: ContactPerson[]
  customerSource: string
  responsibleSalesman: string
  creditRating: string
  creditScore: number
  customerValue: number
  orderCount: number
  totalAmount: number
  avgOrderAmount: number
  overdueAmount: number
  uninvoicedAmount: number
  lastOrderDate: string
  remark: string
  createdAt: string
  // 新增字段以匹配后端返回的数据结构
  customerType: string
  customerLevel: string
}

const props = defineProps<{
  modelValue: boolean
  customerData: Customer | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'edit', customer: Customer): void
  (e: 'close'): void
}>()

const visible = ref(false)
const loading = ref(false)
const activeTab = ref('basic')

const customer = ref<CustomerDetail>({
  id: '',
  name: '',
  code: '',
  type: 'enterprise',
  level: 'normal',
  status: 'active',
  contactPersons: [],
  customerSource: 'self',
  responsibleSalesman: '',
  creditRating: 'A',
  creditScore: 80,
  customerValue: 3,
  orderCount: 0,
  totalAmount: 0,
  avgOrderAmount: 0,
  overdueAmount: 0,
  uninvoicedAmount: 0,
  lastOrderDate: '',
  remark: '',
  createdAt: '',
  // 新增字段
  customerType: '企业客户',
  customerLevel: '普通'
})

// 监听modelValue变化
watch(() => props.modelValue, (newValue: boolean) => {
  visible.value = newValue
})

// 监听visible变化
watch(visible, (newValue: boolean) => {
  emit('update:modelValue', newValue)
})

// 监听客户数据变化
watch(() => props.customerData, (newVal: Customer | null) => {
  if (newVal) {
    // 将后端数据映射到详情字段
    customer.value = {
      ...newVal,
      contactPersons: newVal.contactPersons && Array.isArray(newVal.contactPersons) ? 
        newVal.contactPersons : [],
      // 确保客户类型和等级字段正确映射
      type: newVal.customerType === '企业客户' ? 'enterprise' : 
                   newVal.customerType === '个人客户' ? 'individual' : 
                   newVal.customerType === '政府客户' ? 'government' : 'education',
      level: newVal.customerLevel === 'VIP' ? 'vip' : 
                    newVal.customerLevel === '重要' ? 'important' : 
                    newVal.customerLevel === '普通' ? 'normal' : 
                    newVal.customerLevel === '潜在' ? 'potential' : 'normal',
      // 客户状态映射：1-合作中, 2-暂停合作, 3-已终止, 4-风险客户
      status: parseInt(newVal.status as any) === 1 ? 'active' : 
              parseInt(newVal.status as any) === 2 ? 'suspended' : 
              parseInt(newVal.status as any) === 3 ? 'terminated' : 
              parseInt(newVal.status as any) === 4 ? 'risk' : 'active'
    }
  }
}, { immediate: true })

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

// 格式化金额
const formatAmount = (amount: number) => {
  if (amount === null || amount === undefined) return '0.00'
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 获取客户类型文本
const getCustomerTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'enterprise': '企业客户',
    'government': '政府客户',
    'education': '教育客户',
    'individual': '个人客户'
  }
  return typeMap[type] || type
}

// 获取客户等级文本
const getCustomerLevelText = (level: string) => {
  const levelMap: Record<string, string> = {
    'vip': 'VIP客户',
    'important': '重要客户',
    'normal': '普通客户',
    'new': '新客户'
  }
  return levelMap[level] || level
}

// 获取客户状态类型
const getCustomerStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'active': 'success',
    'inactive': 'info',
    'risk': 'warning',
    'blacklist': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取客户状态文本
const getCustomerStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'active': '合作中',
    'inactive': '暂停合作',
    'risk': '风险客户',
    'blacklist': '黑名单'
  }
  return statusMap[status] || status
}

// 获取客户来源文本
const getCustomerSourceText = (source: string) => {
  const sourceMap: Record<string, string> = {
    'zcy': '政采云',
    'referral': '推荐',
    'self': '自主开发',
    'other': '其他'
  }
  return sourceMap[source] || source
}

// 处理关闭
const handleClose = () => {
  visible.value = false
  emit('close')
}

// 处理编辑
const handleEdit = () => {
  if (props.customerData) {
    emit('edit', props.customerData)
  }
}
</script>

<style scoped>
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>